/*本模块功能:消息通知
        编写者:朱光曜
        编写时间:2017.11.20*/
$(function() {
    var Alert1 = new Alert;
    var confirm1 = new Confirm();
    var confirm2 = new Confirm();
    var roleId =result.paramData.roleId;
    var emp = false; //判断是否清空需要传后台
    function formatDate(now) {//处理时间戳
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var hour = now.getHours();
        var minute = now.getMinutes();
        if(month<10){month="0"+month;}
        if(date<10){date="0"+date;}
        if(hour<10){hour="0"+hour;}
        if(minute<10){minute="0"+minute;}
        return year + "-" + month + "-" + date;
    }
    var string1 = '<tr>' +
        '<th class="col-lg-9">消息通知</th>' +
        '<th class="col-lg-4">开始时间</th>' +
        '<th class="col-lg-4">结束时间</th>' +
        '<th class="col-lg-3">操作</th>' +

        '</tr>';

    function tabelModel(data) {//列表内容
        var releaseTime = new Date(data.adminAndTeaNoticeList[key].releaseTime);
        var endTime=new Date(data.adminAndTeaNoticeList[key].endtime);
        var noticeContent =  data.adminAndTeaNoticeList[key].noticeContent.replace(/<br>/g,"\n");
        return '<tr noticeId="'+data.adminAndTeaNoticeList[key].noticeId+'" >' +
            '<td class="col-lg-9 noticeContent" title="' + noticeContent+ '">' + noticeContent+ '</td>' +
            '<td class="col-lg-9 startTime" title="' + formatDate(releaseTime)+ '">' + formatDate(releaseTime)+ '</td>' +
            '<td class="col-lg-9 endTime" title="' + formatDate(endTime)+ '">' + formatDate(endTime)+ '</td>' +
            '<td class="col-lg-2" ><a	href="javascript:void(0)" class="preservationSet">修改</a><a 	href="javascript:void(0)" class="clearMessage">删除</a></td>' +
            '</tr>';

    }
    function selectClass(data) {//班级内容
        var str = "";
        for(key in data.classList) {
            str += '<div><input value="0" name="selecteds" type="checkbox" class="oneCheck" id="num' + data.classList[key].classId + '" classId="' + data.classList[key].classId + '"/><label for="num' + data.classList[key].classId + '">' + data.classList[key].className + '</label></div>';
        }
        return str;
    }
    var loading1 = new Loading();//监控全局ajax添加loading
    loading1.init();
    $(document).ajaxSend(function(){
        loading1.show();

    });
    $(document).ajaxStop(function(){
        loading1.hide();

    });

    $("textarea").attr("maxlength","100");
    $.map($("textarea"),function (opt) {//长度限制
        maxLengthLimit.init(opt);
    });
    $("textarea").bind('input propertychange',function(){//textarea去除空格

        var regy = /\s/g;
        if(regy.test($(this).val())){
            $(this).val($(this).val().replace(/\s|\xA0/g,"")) ;
        }
    });

    var index = {
        init: function() {
            this.bind();
        },
        bind: function() {
            var self = this;
            //roleId=2;


            /*if(roleId == 2) { //跟据身份判断权限(教师)
                self.loadClass();
                $(".selectClass").show(0);
            } else if(roleId == 3 || roleId == 4) { //(管理员)
                self.loadClass();
            }*/
            datePicker.datePickerMonth($(".form_date"));//时间插件
            this.parameter = {
                "pageNow": 1,
                "pageSize": 10
            };
            this.postData(this.parameter);
            $(".messageRelease").off("click").click(function(){

                var par={
                    "type":2
                };
                self.loadClass(par);

            });

            $(".preservation").off("click").click(function() { //点击提交

                self.delListEvent($(".popup_contenthead .tit_con").attr("type"));

                /*var noticeContent = $(".messageNotificationConText textarea").val();
                var n = /^[1-9]\d*$|^0$/;
                var retain = Number($("#storageDays").val());
                var parame = {

                    "noticeContent": noticeContent,
                    "retain": retain
                }

                if(retain == "") {
                    self.alert1("请输入保存天数");
                } else if(!n.test(retain)) {
                    self.alert1("请输入数字天数");
                } else if(noticeContent == "") {
                    self.alert1("请输入消息内容");
                } else if(verification.specialCode(noticeContent) !== true) {
                    self.alert1("不能输入特殊字符(@/'\"#$%&^*)");
                } else if(verification.spaceCode(noticeContent) !== true) {
                    self.alert1(verification.spaceCode(noticeContent));
                } else {
                    confirm1.content = "确定发送这条消息通知吗"
                    confirm1.success = function() {
                        self.delivery("addNoticeSet", parame);
                    };
                    confirm1.fail = function() {

                    };
                    confirm1.init();
                    confirm1.show();

                }
            */

            });
        },
        postData: function(par_data, nowData, hunt) { //获得搜索及列表数据
            var self = this;
            var parameter = par_data;

            $.ajax({
                type: "post",
                url: "getNoticeListByAdminAndTeaId",
                async: true,
                data: {
                    "jsonStr": JSON.stringify(parameter)
                },
                success: function(data, status, xhr) {
                    var new_data = JSON.parse(data);
                    self.tab_content = new_data;
                    self.tab_add();

                    var sumpage = new_data.totalPage;
                    if(sumpage<1){sumpage=1;};
                    var nowpage = 1;
                    var pagenumber = 10;
                    var parame = parameter;
                    $(".tcdPageCode").createPage({
                        pageCount: sumpage, //总页数
                        current: nowpage, //当前页数
                        pageNumber: pagenumber, //每页显示数量
                        backFn: function(p) {

                            nowpage = p;

                            if(nowpage >= sumpage) {
                                nowpage = sumpage;
                            }
                            parameter.pageNow = nowpage;

                            $.ajax({
                                type: "post",
                                url: "getNoticeListByAdminAndTeaId",
                                async: true,
                                data: {
                                    "jsonStr": JSON.stringify(parameter)
                                },
                                async: true,
                                success: function(msg) {
                                    //获取院系
                                    var msgNew = JSON.parse(msg);
                                    self.tab_content = msgNew;

                                    self.tab_add();
                                },
                                error: function(data, status, xhr) {
                                    var json = JSON.stringify({
                                        "pageName": "error"
                                    });
                                    window.location.href = "skipPage?jsonStr=" + json;

                                }
                            });
                        }
                    });
                },
                error: function(data, status, xhr) {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;

                }
            });

        },
        loadClass: function(par,point) { //加载班级和内容
            var self = this;




            //$(".clearMessage").attr("noticeId", msgNew.noticeMap.noticeId);




            $("#storageDays").val("");
            $("#startTime").val("");
            $(".messageNotificationConText textarea").val("");
            $("#Popup").show();
            $("#popupBackground").css("display","block");
            if(par.type==2){
                $(".popup_contenthead .tit_con").text("发布消息").attr("type",par.type);
            }else{
                var noticeContent=point.parents("tr").children(".noticeContent").html();
                var time =point.parents("tr").children(".endTime").html();
                var start = point.parents("tr").children(".startTime").html();
                $("#storageDays").val(time);
                $("#startTime").val(start);
                $(".messageNotificationConText textarea").val(noticeContent.replace(/<br>/g,"\n"));

                $(".popup_contenthead .tit_con").text("修改消息").attr("type",par.type);

            }
            $("#Popup .popup_contenthead .fr").off("click").click(function(){
                $("#Popup").hide();
                $("#popupBackground").css("display","none");
            });

        },
        tab_add: function() { //列表追加

            var self = this;
            var data = self.tab_content;
            var table = string1;

            //data.selectList={};

            var i = 0;
            for(key in data.adminAndTeaNoticeList) {
                i++;
            }

            if(i > 0) {

                for(key in data.adminAndTeaNoticeList) {

                    table += tabelModel(data);
                }

                $(".mainContent .tableBox").html(table);


                //设置列表宽度(最大为9)
                var numMax = 0;
                $(".tableBox tr:first td").each(function() {
                    var str = $(this).attr("class");
                    var num = str.lastIndexOf("col-lg-") + 7;
                    var num1 = parseFloat(str.substring(num, num + 1));
                    numMax += num1;
                });

                $(".tableBox tr:first td").each(function() {
                    var str = $(this).attr("class");
                    var num = str.lastIndexOf("col-lg-") + 7;
                    var num1 = parseFloat(str.substring(num, num + 1));

                    $(this).css("width", num1 / numMax * 100 + "%");
                });
            } else {
                var trImg = "<tr><td colspan='6' style='border:none;'><img style='margin: 80px auto 20px;' src='pc/images/ico_noneData.png'><p style='font-size:26px;color:#8a8a8a;width:100%;text-align:center;'>暂无消息</p></td/tr>";
                $(".mainContent .tableBox").html(string1+trImg);
            }
            $(".preservationSet").off("click").click(function(){//编辑消息
                $(".popup_contenthead .tit_con").attr("noticeid",$(this).parents("tr").attr("noticeId"));
                var par={
                    "type":1,
                    "noticeId":$(this).parents("tr").attr("noticeId")
                };
                self.loadClass(par,$(this));

            });
            $(".clearMessage").off("click").click(function() { //删除消息
                var $self = self;
                var parameter = {
                    "noticeId": Number($(this).parents("tr").attr("noticeId"))
                };
                var delMessage=function(){


                    $.ajax({
                        type: "post",
                        url: "delNoticeSet",
                        async: true,
                        data: {
                            "jsonStr": JSON.stringify(parameter)
                        },

                        success: function(msg) {

                            var msgNew = JSON.parse(msg);
                            var self = $self;
                            if(msgNew.result == "success") {
                                self.alert1("删除成功","success");

                            } else {
                                if(msgNew.errorMsg){
                                    self.alert1(msgNew.errorMsg);
                                }else{
                                    self.alert1("删除失败");
                                }
                            }
                            //window.location.reload();
                        },
                        error: function(data, status, xhr) {
                            var json = JSON.stringify({
                                "pageName": "error"
                            });
                            window.location.href = "skipPage?jsonStr=" + json;

                        }
                    });
                };
                self.confirm2("是否删除此条消息",delMessage);
            });
        },
        confirm2: function(content1,method) { //confirm提示

            confirm2.contenthead = "提示";
            confirm2.content = content1;

            confirm2.success = method;

            confirm2.init();
            confirm2.show();
        },
        delivery: function(urls, parameter) { //提交保存信息
            var $self = this;


            $.ajax({
                type: "post",
                url: urls,
                async: true,
                data: {
                    "jsonStr": JSON.stringify(parameter)
                },

                success: function(msg) {

                    var msgNew = JSON.parse(msg);
                    var self = $self;
                    if(msgNew.result == "success") {
                        self.alert1("发布成功","success");

                    } else {
                        if(msgNew.failMsg){
                            self.alert1(msgNew.failMsg);
                        }else{
                            self.alert1("删除失败");
                        }

                    }

                },
                error: function(data, status, xhr) {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;

                }
            });
        },
        alert1: function(content1,state) { //confirm提示

            Alert1.contenthead = "提示";
            Alert1.content = content1;

            Alert1.success = function() {
                if(state=="success"){
                    window.location.reload();
                }

                Alert1.hide();
            };

            Alert1.init();
            Alert1.show();
        },
        delListEvent: function(type) { //选择班级
            var classList = [];
            var self = this;
            $(".oneCheck[value=1]").each(function() {
                if(parseInt($(this).val()) == 1) {
                    classList.push($(this).attr("classId"));
                }
            });
            var noticeContent = $(".messageNotificationConText textarea").val();
            var n = /^[1-9]\d*$|^0$/;
            var endtime = $("#storageDays").val();
            var startTime = $("#startTime").val();
            var myDate=new Date();
            if(type==1){
                var parame = {
                    "noticeContent": noticeContent,
                    "releaseTime":startTime,
                    "noticeId":$(".popup_contenthead .tit_con").attr("noticeid"),
                    "endtime": endtime,
                    "operateMark":type
                };
            }else{
                var parame = {
                    "noticeContent": noticeContent,
                    "releaseTime":startTime,
                    "endtime": endtime,
                    "operateMark":type
                };
            }
            if(startTime == "") {
                self.alert1("请选择开始时间");
            } else if(endtime == "") {
                self.alert1("请选择结束时间");
            } else if(endtime.replace(/-/g,"")<startTime.replace(/-/g,"")) {
                self.alert1("结束时间不能在开始时间之前");
            }else if(noticeContent == "") {
                self.alert1("请输入消息内容");
            } else if(verification.specialCode(noticeContent) !== true) {
                self.alert1("不能输入特殊字符(@/'\"#$%&^*)");
            } else {
                var j=0;
                for(i in parame){//遍历改变数字

                    if(j==0){j++;continue;}
                    if(!isNaN(parame[i])&&!$.isArray(parame[i])){
                        parame[i]=Number(parame[i]);
                    }
                }


                confirm1.contenthead = "提示消息";
                confirm1.content = "确定发送这条消息通知吗？";
                confirm1.success = function() {
                    self.delivery("addNotice", parame);
                };
                confirm1.fail = function() {

                };
                confirm1.init();
                confirm1.show();

            }


        },
        allCheckEvent: function() {
            //全选
            allCheck.init("controlAll", "oneCheck");
        }

    };
    index.init();

});